﻿#region Imports

using System;
using System.Collections;
using Spring.DataBinding;
using Spring.Validation;
using d3PrtDgn.Common.Common;
using d3PrtDgn.Data.IDAO;

#endregion

namespace d3PrtDgn.Web
{
	/// <summary>
	/// Login page
	/// </summary>
	public partial class LoginPage : Page
	{
		#region Private fields
		private IUserDao userDao;
		private d3PrtDgn.Data.Domain.Entity.User logUser;
		private IValidator loginValidator;
		#endregion

		#region Public properties
		/// <summary>
		/// User who is trying to register
		/// </summary>
        public Data.Domain.Entity.User LogUser
		{
			get { return logUser; }
			set { logUser = value; }
		}

		/// <summary>
		/// Access object for user
		/// </summary>
		public IUserDao UserDao
		{
			set { userDao = value; }
		}

		/// <summary>
		/// Login form validator
		/// </summary>
		public IValidator LoginValidator
		{
			set { this.loginValidator = value; }
		}
		#endregion

		#region Model Management and Data Binding Methods
		protected override void InitializeModel()
		{
            logUser = new Data.Domain.Entity.User();
		}

		protected override void LoadModel(object savedModel)
		{
            logUser = (Data.Domain.Entity.User)savedModel;
		}

		protected override object SaveModel()
		{
			return logUser;
		}

		protected override void InitializeDataBindings()
		{
			BindingManager.AddBinding("tbUsername.Text", "LogUser.Username");
			BindingManager.AddBinding("@(TextUtil).GetMd5Hash(tbPassword.Text)", "LogUser.Password", BindingDirection.SourceToTarget);
		}
		#endregion

		#region Event handlers

		/// <summary>
		/// Handles page load event
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void Page_Load(object sender, EventArgs e)
		{
			// just registered
			bool registered;
			lblSuccessfulyRegistered.Visible = (Request.Params["registered"] != null && bool.TryParse(Request.Params["registered"], out registered));

			// login failed
			bool failed;
			lblLoginFailed.Visible = (Request.Params["failed"] != null && bool.TryParse(Request.Params["failed"], out failed));

			// logging out
			bool logout;
			if (Request.Params["logout"] != null && bool.TryParse(Request.Params["logout"], out logout))
			{
				((Hashtable)Session["spring.objects"])["signedInUser.spring"] = null;
				SetResult("HomePage");
			}

			// redirecting from another page in order to log in
			lblNeedToLogin.Visible = Request.Params["redirectUrl"] != null;
		}

		/// <summary>
		/// Handles login button click event
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void btnLogin_Click(object sender, EventArgs e)
		{
			if (Validate(logUser, loginValidator))
			{
                Data.Domain.Entity.User usr = userDao.Authenticate(logUser);
				if (usr != null)
				{
					/*
					 * HACK: why cannot modify session scoped object from here just using
					 * SignedInUser = usr? http://forum.springframework.net/showthread.php?t=85
					 */
					((Hashtable)Session["spring.objects"])["signedInUser.spring"] = usr;

					if (Request.Params["redirectUrl"] != null)
					{
						Response.Redirect(Request.Params["redirectUrl"]);
					}
					else
					{
						SetResult("HomePage");
					}
				}
				else
				{
					((Hashtable)Session["spring.objects"])["signedInUser.spring"] = null;
					SetResult("LoginFailed");
				}
			}
		}

		#endregion
	}
}